<?php
/**
 * Created by PhpStorm.
 * User: qch
 * Date: 2015/9/20
 * Time: 20:37
 */

namespace Application\Common\Controller;


use J\Schema\ICurd;
use J\Schema\Sprite;
use J\Schema\Syntax;
use J\Exception;
use J\Intent;
use J\Message;
use J\Util\Node;
use J\Util\Tree;


/**
 * Vue自动处理
 *
 */
class ElementUIActor extends AutoActor
{
    /**
     * @var ElementUIController
     */
    protected $controller;
    /**
     * ElementUI中间件
     *
     * @inheritdoc
     * @throws Exception
     */
    protected function invokeIntentMethod(Intent $intent)
    {
        $config = $this->controller->getInformation($intent);

        if (__OPTION__ === 'ElementUI') {
            $intent->value =  ElementUI::getView($this->controller, $intent, $config, $this->getModel());
        } elseif (__OPTION__ === 'Data') {
            $where = array_isset($config, 'where', []);
            $intent->value = $this->getData($config, $where);
        } else {
            parent::invokeIntentMethod($intent);
        }
    }

    /**
     * 获取数据，自动构造树
     *
     * @param array $config
     * @param array $where
     * @return array
     * @throws Exception
     */
    protected function getData($config, $where = [])
    {
        // 返回结构判断
        $tree = $this->getModel()->getTreeKey();
        // 返回值
        $return = [];
        // 用于树状结构
        $key = null;

        $curd = $this->getModel()->getCurd();
        // 页面查询
        $search = $this->getSearch(array_isset($config, 'search', []), $where);
        // 设置查询
        $curd->setWhere($search);
        // 查询列表
        $elements = get_elements($config);

        if (!$tree) {
            $return = $this->getOption($return, $curd, $config);
        } else {
            // 修正查询域
            $key = $this->getModel()->getKey();
            $return['labelKey'] = $key;
            $elements[] = $key;
            // $pid = $this->getModel()->getTreeKey();
            $return['pidKey'] = $this->getModel()->getName();
            $elements[] = $tree;
            // 修正查询处理
            $curd->setRaw(true);
        }

        $values = $curd->setElements($elements)->select();

        if (empty($values)) return [];

        $return['status'] = 1;

        if (!$tree) {
            $return['rows'] = array_values($values);
        } else {
            $objTree = new Tree();

            $drawer = function (Node $node) use ($key) {
                $row = $node->update();
                $row['label'] = $row[$key];
                $row['index'] = $row[Syntax::KEY_ID];
                $row['value'] = $row[Syntax::KEY_ID] + 0;
                return $row;
            };
            $rows = $objTree->fromList($values, $tree)
                ->getRoot()->map($drawer, 'children');

            $return['rows'] = array_isset($rows, 'children', []);
        }

        return $return;
    }

    protected function getOption($return, ICurd $curd, $config)
    {
        $option = $curd->getOption();
        //分页
        $size = array_isset($config, 'size', 10);
        if ($size > 0) {
            $return['total'] = $curd->setElements([Syntax::KEY_ID])->count();
            $page = (int)(array_isset($_REQUEST, 'page', 1));
            $option->page($page, $size);
            $return['page'] = $page;
            $return['size'] = $size;
        }
        //排序
        if (isset($_REQUEST['sort']['column'])) {
            try {
                $col = $this->getModel()->elements()->getElementByFieldName($_REQUEST['sort']['column']);
                $order = array_isset($_REQUEST['sort'], 'order', '');
                $order = ($order !== 'descending');
                $option->orderBy([$col->getName(), ($order !== 'descending')]);
            } catch (\Throwable $e) {

            }
        }

        return $return;
    }

    /**
     * 构造查询语句
     *
     * @param array $search
     * @param array $where
     * @return array
     * @throws Exception
     */
    protected function getSearch($search, $where = [])
    {
        $search_elements = array_isset($search, Syntax::KEY_ELEMENTS, []);

        $search_elements = array_complete($search_elements, '=');

        // 查询前置条件
        $map = $where;
        // 查询，树查询语法糖用于单表存储分开不同的树
        if (
            isset($_REQUEST['search']) and
            is_array($_REQUEST['search'])

        ) {
            foreach ($_REQUEST['search'] as $name => $value) {
                if (!isset($search_elements[$name])) continue;
                $element = $this->getModel()->elements()->getElementByFieldName($name);
                if ($element and $this->controller->parseInputValue($value, $name)) {
                    $map[] = new Sprite($element->getName(), $value, $search_elements[$name]);
                }
            }
        }

        $map[] = new Sprite('status', 0, '>');

        return $this->filterAdd($map);
    }

    /**
     * 获取ID
     * @param string $key
     * @return int
     * @throws Exception
     */
    protected function findId($key = Syntax::KEY_ID)
    {
        if(isset($_REQUEST[$key])) {
            $id = (int)($_REQUEST[$key]);

            if ($id > 0) return $id;
        }
        throw new Exception(Message::ID_NOT_INPUT);
    }

    /**
     * 跳转
     *
     * @param Intent $intent
     * @param string $msg
     */
    protected function next($intent, $msg)
    {
        $next = $this->controller->getInformation($intent, 'next', false);
        $data = [];
        if($next)
            $data['next'] = $intent->makeUrl($next, '/element.php');

        $intent->ajax(true, $msg, $data);
    }


}
